<template>
	<section>
		<!--工具条-->

		<div class="section-content clearfix">
			<el-col :span="24" class="" style="padding-bottom: 0px;">
				<el-form :inline="true" :model="filters"> 
					
					<el-form-item>
						<el-select v-model="filters.name" placeholder="设备名称" filterable @change="nameget()">
							<el-option  label="所有" value=" "></el-option>
							<el-option v-for="item in devicelist" :key="item.id" :label="item.name"
								:value="item.name">
							</el-option>
						</el-select>
					</el-form-item>

					
						<el-select style="margin-right:10px" v-if="usertype==2" v-model="scade1" filterable placeholder="组织名称"
							@change="select_scade1()">
							<el-option key="" label="全选" value=" "></el-option>
							<el-option v-for="item in firmlist" :key="item.companyId" :label="item.name"
								:value="item.companyId">
							</el-option>
						</el-select>
					
					<!-- <el-form-item>
						<el-select v-model="scade" filterable placeholder="请选择子用户" size="" @change="deviceList()">
							<el-option :key="scade1" label="当前账户" :value="scade1">
							</el-option>
							<el-option v-for="item in userclist" :key="item.userId" :label="item.userName"
								:value="item.userId">
							</el-option>
						</el-select>
					</el-form-item> -->
					<el-form-item style="">
						<el-select v-model="filters.deviceSn" placeholder="网关SN" filterable 
							@change="snget()">
							<el-option  key="" label="所有" value=" "></el-option>
							<el-option v-for="item in devicelist" :key="item.deviceSn" :label="item.deviceSn"
								:value="item.deviceSn">
							</el-option>
						</el-select>
					</el-form-item>
					<el-select v-model="filters.state" placeholder="上下线" @change="getUsers()">

						<el-option label="全选" value=" "></el-option>

						<el-option label="上线" key="1" value="1"></el-option>

						<el-option label="下线" key="0" value="0"></el-option>
					</el-select>
					<el-form-item style="margin-left:10px">
						<el-date-picker v-model="value4" @change="second1()" type="datetimerange" range-separator="至"
							start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions2">
						</el-date-picker>
					</el-form-item>
					<el-form-item>
						<el-button :type="buttonColor" v-on:click="getUsers">查询</el-button>
					</el-form-item>
					<el-form-item>

						<el-button :type="buttonColor" @click="tableToExcel(item)">导出历史数据</el-button>
						<!-- <el-button type="primary" @click="handleAdd">新增</el-button> -->
					</el-form-item>
					<el-form-item>
						上线:{{onlineCount}}
					</el-form-item>
					<el-form-item>
						下线:{{offlineCount}}
					</el-form-item>
				</el-form>
			</el-col>

			<!--列表-->
			<el-table :data="query" highlight-current-row v-loading="listLoading" @selection-change="selsChange" :header-row-style="{backgroundColor: titleColor}" style="width: 100%;">
				<!-- <el-table-column type="selection">
				</el-table-column> -->
				<el-table-column align="center" type="index" label="序号" width="80" :index="indexMethod">
				</el-table-column>,
				<el-table-column align="center" prop="name" label="设备名称">
				</el-table-column>
				<el-table-column align="center" prop="deviceSn" label="网关SN">
				</el-table-column>
				<el-table-column align="center" prop="createTime" label="时间">
				</el-table-column>
				<el-table-column align="center" prop="stateText" label="状态">
				</el-table-column>

			</el-table>

			<!--工具条-->
			<el-col :span="24" class="toolbar">
				<!-- <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button> -->

				<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10"
					:total="total" style="float:right;">
				</el-pagination>
			</el-col>
		</div>
		<!--编辑界面-->
		<el-dialog title="编辑" v-show="editFormVisible" v-model="editFormVisible" @close="editFormVisible=false">
			<div slot="footer" style="text-align: left; ">
				<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
					<el-form-item label="名字" prop="name">
						<el-input v-model="editForm.name" auto-complete="off"></el-input>
					</el-form-item>
					<el-form-item label="电话号码" prop="">
						<el-input v-model="editForm.phone"></el-input>
					</el-form-item>
					<el-form-item label="email" prop="">
						<el-input v-model="editForm.email"></el-input>
					</el-form-item>
					<el-form-item label="微信" prop="">
						<el-input v-model="editForm.weixin"></el-input>
					</el-form-item>
					<el-form-item label="备注" prop="remark">
						<el-input type="textarea" v-model="editForm.remark"></el-input>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer" style="text-align:right;">
					<el-button @click.native="editFormVisible = false">取消</el-button>
					<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
				</div>
			</div>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增" v-show="addFormVisible" v-model="addFormVisible" @close="addFormVisible=false">
			<div slot="footer" style="text-align: left; ">
				<el-form :model="addForm" label-width="100px" :rules="addFormRules" ref="addForm">
					<el-form-item label="设备模板名称" prop="name">
						<el-input v-model="addForm.name" auto-complete="off"></el-input>
					</el-form-item>
					<el-form-item label="设备类型">
						<el-input v-model="addForm.deviceTypeId" auto-complete="off"></el-input>
					</el-form-item>
					<el-form-item label="组织用户">
						<el-input v-model="addForm.vendorUserId" auto-complete="off"></el-input>
					</el-form-item>
					<el-form-item label="设备所属用户">
						<el-input v-model="addForm.deviceUserId" auto-complete="off"></el-input>
					</el-form-item>
					<el-form-item label="移动属性">
						<el-input v-model="addForm.moving" auto-complete="off"></el-input>
					</el-form-item>
					<el-form-item label="订单号">
						<el-input v-model="addForm.orderSn" auto-complete="off"></el-input>
					</el-form-item>
					<el-form-item label="行业" prop="guild">
						<el-input v-model="addForm.guild" auto-complete="off"></el-input>
					</el-form-item>
					<el-form-item label="区域">
						<el-input v-model="addForm.area" auto-complete="off"></el-input>
					</el-form-item>
					<el-form-item label="是否默认">
						<el-input v-model="addForm.isDefault" auto-complete="off"></el-input>
					</el-form-item>
					<el-form-item label="省">
						<el-input v-model="addForm.province" auto-complete="off"></el-input>
					</el-form-item>
					<el-form-item label="市">
						<el-input v-model="addForm.city" auto-complete="off"></el-input>
					</el-form-item>
					<el-form-item label="备注" prop="remark">
						<el-input v-model="addForm.remark" auto-complete="off"></el-input>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer" style="text-align: right;">
					<el-button @click.native="addFormVisible = false">取消</el-button>
					<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
				</div>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	// import util from './../common/js/util'
	//import NProgress from 'nprogress'
	import {
		device_state_log_query,
		device_template_post,
		device_template_put,
		device_template_get,
		device_template_delete,
		device_query_mini,
		device_state_log_dlexcel,
		user_querycompany,
		user_query
	} from '../../api/api';

	export default {
		data() {
			return {
				userID: '',
				scade1: '',
				firmlist: '',
				onlineCount:'',//在线
				offlineCount:'',//离线
				pickerOptions2: {
					shortcuts: [{
						text: '最近1小时',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 1);
							picker.$emit('pick', [start, end]);
						}
					}, {
						text: '最近24小时',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
							picker.$emit('pick', [start, end]);
						}
					}, {
						text: '最近一周',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
							picker.$emit('pick', [start, end]);
						}
					}, {
						text: '最近一个月',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
							picker.$emit('pick', [start, end]);
						}
					}]
				},
				scade: '',
				value4: [new Date().getTime() - 3600 * 1000 * 24 * 1, new Date()],
				filters: {

					startTime: '',
					endTime: '',
					name: '',
					deviceSn: '',
					state: ''

				},
				query: [],
				total: 0,
				page: 1,
				listLoading: false,
				sels: [], //列表选中列

				editFormVisible: false, //编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [{
						required: true,
						message: '请输入姓名',
						trigger: 'blur'
					}, {
						min: 1,
						max: 20,
						message: '长度在 1 到 20 个字符',
						trigger: 'blur'
					}]
				},
				devicelist: [],
				//编辑界面数据
				editForm: {
					id: '',
					name: '',
					deviceTypeId: '',
					vendorUserId: '',
					deviceUserId: '',
					moving: '',
					orderSn: '',
					guild: '',
					area: '',
					isDefault: '',
					province: '',
					city: '',
					remark: ''
				},

				addFormVisible: false, //新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [{
						required: true,
						message: '请输入姓名',
						trigger: 'blur'
					}, {
						min: 1,
						max: 20,
						message: '长度在 1 到 20 个字符',
						trigger: 'blur'
					}],
					path: [{
							required: true,
							message: '请输入path',
							trigger: 'blur'
						}

					]
				},
				//新增界面数据
				addForm: {
					name: '',
					deviceTypeId: '',
					vendorUserId: '',
					deviceUserId: '',
					moving: '',
					orderSn: '',
					guild: '',
					area: '',
					isDefault: '',
					province: '',
					city: '',
					remark: ''
				},
				usertype: ''


			}
		},
		computed:{
            buttonColor(){
                return this.$store.state.buttonColor
            },
            titleColor(){
                return this.$store.state.titleColor
            },
        },
		methods: {
			indexMethod(index) {
				let num = (this.page - 1) * 10 + index + 1;
				return num;
			},
			download(data) {
				if (!data) {
					return
				}
				let url = window.URL.createObjectURL(new Blob([data]))
				let link = document.createElement('a');
				link.style.display = 'none';
				link.href = url;
				link.setAttribute('download', 'excel.xlsx');

				document.body.appendChild(link);
				link.click();
			},
			tableToExcel(s) {
				let para = {
					pageNo: 1,
					pageSize: 10000,
					name: this.filters.name,
					deviceSn: this.filters.deviceSn,
					state: this.filters.state,
					startTime: this.filters.startTime,
					endTime: this.filters.endTime
				};
				//NProgress.start();
				device_state_log_dlexcel(para).then((res) => {
					this.download(res)
					//NProgress.done();
				});
			},
			nameget() {
				this.filters.deviceSn = '';
				this.getUsers();
			},
			snget() {
				
				this.filters.name = '';
				this.getUsers();
			},
			getdata(date) {

				var y = date.getFullYear();
				var m = date.getMonth() + 1;
				m = m < 10 ? ('0' + m) : m;
				var d = date.getDate();
				d = d < 10 ? ('0' + d) : d;
				var h = date.getHours();
				h = h < 10 ? ('0' + h) : h;
				var minute = date.getMinutes();
				minute = minute < 10 ? ('0' + minute) : minute;
				var second = date.getSeconds();
				second = second < 10 ? ('0' + second) : second;
				return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;

			},
			//性别显示转换
			second1() {

				this.filters.startTime = this.getdata(this.value4[0]);
				this.filters.endTime = this.getdata(this.value4[1]);
				console.log(this.filters.startTime)
			},
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getUsers();
			},
			//获取菜单列表
			getUsers() {

				let para = {
					pageNo: this.page,
					pageSize: 10,
					name: this.filters.name,
					deviceSn: this.filters.deviceSn,
					state: this.filters.state,
					companyId: this.scade1,
					startTime: this.filters.startTime,
					endTime: this.filters.endTime,
					// queryUserId: this.scade
				};
				this.listLoading = true;
				//NProgress.start();
				device_state_log_query(para).then((res) => {
					this.begCode(res.code, res.message);
					this.total = res.data.totalCount;
					this.onlineCount = res.data.online
					this.offlineCount = res.data.offline
					this.query = res.data.list;
					this.listLoading = false;
					this.page = res.data.pageNo;

					//NProgress.done();
				});
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = {
						id: row.id
					};
					alarms_delete_user(para).then((res) => {
						this.begCode(res.code, res.message);
						if (res.code == 0) {

							this.listLoading = false;
							//NProgress.done();
							this.$message({
								message: '删除成功',
								type: 'success'
							});
							this.getUsers();

						}
					});
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);
			},
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
				this.addForm = {
					name: '',
					sex: -1,
					age: 0,
					birth: '',
					addr: ''
				};
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.editForm);

							alarms_put_user(para).then((res) => {
								this.begCode(res.code, res.message);

								if (res.code == 0) {
									this.editLoading = false;
									//NProgress.done();
									this.$message({
										message: '提交成功',
										type: 'success'
									});
									this.$refs['editForm'].resetFields();
									this.editFormVisible = false;
									this.getUsers();
								}
							});
						});
					}
				});
			},
			
			select_scade1(s) {
				console.log(this.scade1)
				// let para = {
				// 	pageNo: 1,
				// 	pageSize: 9999,
				// 	type: 0,
				// 	companyId: this.scade1,
                //     authType: 0
				// }
				// console.log(para)
				// user_querycompany(para).then((res) => {
				// 	console.log(res)
				// 	this.begCode(res.code, res.message);
				// 	this.userclist = res.data.list;
				// 	// console.log(this.scade1)
				// 	if (this.scade1) {
				// 		this.userID = this.scade1;
				// 		this.scade = "";
				// 		this.scade=this.scade1;
				// 	} else {
				// 		this.userID = 0;
				// 		// console.log(this.userID)
				// 	}
				// });
				
				this.deviceList();
			},
			
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.addForm);

							alarms_post_user(para).then((res) => {
								this.begCode(res.code, res.message);
								this.addLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['addForm'].resetFields();
								this.addFormVisible = false;
								this.getUsers();
							});
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = {
						ids: ids
					};
					batchRemoveUser(para).then((res) => {
						this.begCode(res.code, res.message);
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getUsers();
					});
				}).catch(() => {

				});
			},
			deviceList() {
				let para = {
					pageNo: 1,
					pageSize: 9999,
					companyId: this.scade1,
					miniLev:2

				};
				device_query_mini(para).then((res) => {
					this.begCode(res.code, res.message); 
					this.devicelist = res.data.list;
					// if (this.devicelist.length > 0) {
					// 	this.filters.name = this.devicelist[0].name;
					// }else{
					// 	this.filters.name='';
					// }

					this.getUsers();
					//NProgress.done();
				});
			}
		},
		mounted() {

			this.usertype = JSON.parse(sessionStorage.getItem('user')).type;
			let para = {
				pageNo: this.page,
				pageSize: 9999

			};
			// let para1 = {
			// 	pageNo: 1,
			// 	pageSize: 9999,
			// 	type: 0,
				
			// 	authType: 0
			// }
			

			// user_query(para1).then((res) => {
			// 	// console.log(res)
			// 	this.begCode(res.code, res.message);
			// 	this.userclist = res.data.list;
			// 	// if (this.userclist[0]) {

			// 	//     this.scade = this.userclist[0].userId;
			// 	// }
			// 	this.scade = this.userID
			// 	// this.select_scade();

			// });
			//NProgress.start();
			let parauser = {
				pageNo: 1,
				pageSize: 9999,
				type: 1,
				companyId:''
			}

			user_querycompany(parauser).then((res) => {
				console.log(res)
				this.begCode(res.code, res.message);
				this.firmlist = res.data.list;
			});

			let start1 = new Date();
			let start2 = new Date();
			start1.setTime(start1.getTime() - 3600 * 1000 * 1 * 1);
			start2.setTime(start2.getTime());

			this.value4 = [this.getdata(start1), this.getdata(start2)];
			this.filters.startTime = this.getdata(start1);
			this.filters.endTime = this.getdata(start2);
			this.deviceList();
		}
	}
</script>

<style scoped>

</style>